<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="iceui/src/ui/ui.css" />
    <link rel="stylesheet" href="layui/css/layui.css" />
    <link rel="stylesheet" href="css/adminXL.css">
    <link rel="stylesheet" href="css/iconfont.css" />
    <link rel="stylesheet" href="css/ViewPost.css" />
    <script src="js/iconfont.js"></script>
    <script src="iceui/src/ice.js"></script>
    <script src="iceui/src/ui/ui.js"></script>
    <script src="iceui/src/popup/icePopup.js"></script>
    <script src="layui/layui.js"></script>
    <script src="js/adminXL.min.js"></script>
    <script src="js/vue.js"></script>
    <script src="js/jquery-1.12.4.js"></script>
    <script src="js/jquery-1.12.4.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .title {
            font-size: 20px;
            color: rgb(14, 0, 0);
        }

        .tree-alone {
            height: 50px;
            line-height: 30px;
        }

        li.test {
            margin-left: 15px;
        }

        .userinfo:hover {
            background-color: rgb(196, 196, 196);
        }
    </style>
</head>

<body>
    <div class="layui-row layui-col-space5">
        <div class="layui-col-md4">
            <div class="grid-demo grid-demo-bg1" style="width:375.7px;height:740px;">
                <div class="left" style="width:375.7px;height:100%;display:inline-block;">
                    <div class="adminXL-sidebar close"
                        style="background-color:white;border-right: 1px solid rgb(196, 196, 196);width:375.7px;">
                        <div class="layui-col-xs2" style="width: 375.7px;height: 100px;">
                            <div class="grid-demo grid-demo-bg1">
                                <a href="page/home.html" class="adminXL-logo-web"
                                    style="position: fixed;top: 30px;left: 130px;">
                                    <img src="img/彩云里Logo.jpg" class="logo" alt="RainbowCloud"
                                        style="width: 60px;height:50px;">
                                </a>
                            </div>
                        </div>
                        <ul id="Menu-tree" class="adminXL-sidebar-menu" style="width:375.7px;">
                            <li class="tree-alone" style="font-weight:bold;">
                                <a lay-href="Showpost.html" onclick="window.location='Home.html'">
                                    <i class="icon ice-home"></i>
                                    <span class="title">主页</span>
                                </a>
                            </li>
                            <li class="tree-alone" id="aa">
                                <a href="#" onclick="window.location='Main.html'">
                                    <i class="icon ice-expand"></i>
                                    <span class="title">探索</span>
                                </a>
                            </li>
                            <li class="tree-alone">
                                <a href="#">
                                    <i class="layui-icon layui-icon-notice" style="padding-left:4px;"></i>
                                    <span class="title" style="margin-left:20px;">通知</span>
                                </a>
                            </li>
                            <li class="tree-alone">
                                <a href="#">
                                    <i class="icon ice-message"></i>
                                    <span class="title">私信</span>
                                </a>
                            </li>
                            <li class="tree-alone">
                                <a href="#">
                                    <i class="icon ice-order-out"></i>
                                    <span class="title">列表</span>
                                </a>
                            </li>
                            <li class="tree-alone">
                                <a href="#">
                                    <i class="icon ice-mass"></i>
                                    <span class="title">社群</span>
                                </a>
                            </li>
                            <li class="tree-alone">
                                <a href="#">
                                    <i class="icon ice-category"></i>
                                    <span class="title">Premium</span>
                                </a>
                            </li>
                            <li class="tree-alone">
                                <a href="#" onclick="window.location='Personal.html'">
                                    <i class="icon ice-user"></i>
                                    <span class="title">个人资料</span>
                                </a>
                            </li>
                            <li class="tree-alone">
                                <a href="#">
                                    <i class="icon ice-computer"></i>
                                    <span class="title">更多</span>
                                </a>
                            </li>
                            <button type="button" id="test"
                                class="layui-btn layui-btn-lg layui-btn-primary layui-btn-radius layui-bg-blue"
                                style="width: 200px;height: 50px;margin-left:40px;" id="aa">发帖</button>
                            <div class="userinfo"
                                style="width:243.8px;height:65.26px;margin-left:105px;margin-top:35px;border-radius:30px;display:inline-block;">
                                <div class="userimage"
                                    style="width:220px;height:45px;margin-top:9px;margin-left:9px;display:inline-block;">
                                    <img id="useravatar" style="width:45px;height:45px;border-radius:50%;">

                                    <span style="position:absolute;top:665px;left:170px;font-size:15px;color:#0F1419"
                                        id="nickname"></span>
                                    <span style="position:absolute;top:687px;left:170px;font-size:15px;color:#536471;"
                                        id="username"></span>
                                    <i class="icon ice-dropdown" style="margin-left:132px;"></i>
                                </div>
                            </div>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-col-md4">
            <div class="grid-demo" style="width:598.4px;margin-left:-110px;border-right:1px solid rgb(226,226,226);">
                <div class="centertop">
                    <div class="centericon">
                        <a href="javascript:history.back()"><i class="icon ice-revoke-left"></i></a>
                    </div>
                    <span class="inner">帖子</span>
                </div>
                <div id="container">

                </div>
            </div>
        </div>



        <script>
            layui.use(['flow', 'layer'], function () {
                const urlParams = new URLSearchParams(window.location.search);
                const pid = urlParams.get('pid'); // 获取id参数的值
                // 获取flow模块的对象
                var flow = layui.flow;
                var layer = layui.layer;
                var util = layui.util;
                var $ = layui.jquery;
                let user = JSON.parse(sessionStorage.getItem("user"))
                $("#nickname").text(user.userinfo.nickname)
                $("#username").text("@" + user.username)
                $("#useravatar").prop("src", "data:image/png;base64," + user.avatar)
                // 调用flow的load方法，实现流加载的功能
                // 定义一个变量，用来存储拼接的html字符串
                var html = '';
                // 使用jquery的ajax方法，向后端发送请求，获取数据
                $.ajax({
                    type: "GET",
                    url: "http://169.254.202.137:8080/ViewPost?pid=" + pid, // 后端的Servlet路径，加上页码参数
                    dataType: "json", // 预期返回的数据类型是json
                    success: function (data) {
                        function UTF16Tocontent(str) {
                            return str.replace(/\\u([a-fA-F0-9]{4,5})/g, function (match, grp) {
                                return String.fromCharCode(parseInt(grp, 16));
                            });
                        }
                        function contentToUTF16(str) {
                            var result = "";
                            for (var i = 0; i < str.length; i++) {
                                result += "\\u" + ("000" + str.charCodeAt(i).toString(16)).substr(-4);
                            }
                            return result;
                        }
                        var postidarray = [];
                        var commentidarray = [];
                        var replyidarray = [];
                        // 如果请求成功，遍历返回的数据，将每个帖子和评论的信息拼接成html字符串

                        var post = data.data; // 获取每个帖子对象
                        postidarray.push(post.pid)
                        let date = new Date(post.ptime)
                        // 获取该时间的毫秒数
                        let dateMs = date.getTime();

                        // 获取当前时间的毫秒数
                        let nowMs = Date.now();

                        // 计算两个时间的差值，单位为毫秒
                        let diffMs = nowMs - dateMs;

                        // 将差值除以 1000，得到两个时间的差值，单位为秒
                        let diffSec = Math.floor(diffMs / 1000);

                        // 定义一个空字符串，用于存储拼接的结果
                        let diffStr = "";

                        // 判断差值的大小，拼接成相应的字符串
                        if (diffSec < 60) {
                            // 如果差值小于 60 秒，显示为几秒
                            diffStr = diffSec + "秒前";
                        } else if (diffSec < 3600) {
                            // 如果差值小于 3600 秒，显示为几分钟
                            diffStr = Math.floor(diffSec / 60) + "分钟前";
                        } else if (diffSec < 86400) {
                            // 如果差值小于 86400 秒，显示为几小时
                            diffStr = Math.floor(diffSec / 3600) + "小时前";
                        } else if (diffSec < 604800) {
                            diffStr = Math.floor(diffSec / 86400) + "天前";
                        } else if (diffSec < 31536000) {
                            diffStr = date.getMonth() + 1 + "月" + date.getDate() + "日";
                        } else {
                            diffStr = date.getFullYear() + "年" + (date.getMonth() + 1) + "月" + date.getDate() + "日";
                        }
                        // 拼接帖子的信息
                        html += '<div class="post" id="post-' + post.pid + '" >';
                        html += '<img class="avatar" src="data:image/png;base64,' + post.publishaccountInfo.avatar + '">' + '<p class="user" hidden>' + post.pid + '</p>'
                        html += '<span class="user">' + post.userinfo.nickname + '</span>';
                        html += '<p class="content">' + UTF16Tocontent(post.pcontent) + '</p>';
                        if (post.pimage) { // 如果帖子有图片，显示图片
                            html += '<img class="image" src="data:image/png;base64,' + post.pimage + '">';
                        }
                        if (post.pvideo) { // 如果帖子有视频，显示视频
                            html += '<video class="video" src="http://169.254.202.137:8080/' + post.pvideo + '" controls></video>';
                        }
                        html += '<div class="time"><time class="datetime" datetime="' + post.ptime + '" id="time-' + post.userinfo.useruid + '" lay-src="' + post.ptime + '">' + diffStr + '</time></div>'
                        html += '<div class="useroperate"><div class="likess"><i class="like" :class="likeClass" @click.stop="Like()"></i><span class="likes">{{ likes }}</span></div>';
                        html += '<div class="commentss"><i class="icon ice-message"></i><span class="comments">{{ commentscount }}</span></div><span class="replySelect" @click="selectReplyPid()">回复</span>';
                        html += '</div><div class="postacomment"><img id="pubuseravatar" src="data:image/png;base64,' + user.avatar + '">';
                        html += '<input class="input" type="text" placeholder="发布你的回复"/>'
                        html += '<button class="layui-btn layui-btn-lg layui-btn-primary layui-btn-radius layui-bg-blue" @click = "PubComment()">回复</button></div>';
                        html += '</div>';
                        // 获取帖子的评论数组
                        var comments = post.comments;
                        // 遍历评论数组，拼接评论的信息
                        for (var j = 0; j < comments.length; j++) {
                            var comment = comments[j]; // 获取每个评论对象
                            commentidarray.push(comment.pid);
                            // 拼接评论的信息
                            html += '<div class="comment" id="comment-' + comment.pid + '" >'
                            html += '<img class="commentavatar" src="data:image/png;base64,' + comment.publishaccountInfo.avatar + '">' + '<p class="user" hidden>' + comment.userinfo.useruid + '</p>'
                            html += '<span class="user">' + comment.userinfo.nickname + '</span>';
                            html += '<p class="plcontent">' + UTF16Tocontent(comment.pcontent) + '</p>';
                            html += '<div class="review"><div class="likess"><i class="like" :class="likeClass" @click.stop="Like()"></i><span class="likes">{{ likes }}</span></div>';
                            html += '<div class="commentss"><i class="icon ice-message"></i><span class="comments">{{ commentscount }}</span></div><span class="replySelect" @click="selectReplyPid()">回复</span></div>';
                            html += '</div>';

                            var replys = comment.comments;
                            if (replys == null)
                                continue

                            for (var k = 0; k < replys.length; k++) {
                                var reply = replys[k];
                                replyidarray.push(reply.pid);

                                html += '<div class="reply hiddenReply" id="reply-' + reply.pid + '">';
                                html += '<img class="commentavatar" src="data:image/png;base64,' + reply.publishaccountInfo.avatar + '">' + '<p class="user" hidden>' + reply.userinfo.useruid + '</p>'
                                html += '<span class="user">' + reply.userinfo.nickname + '</span>';
                                html += '<p class="repcontent">' + UTF16Tocontent(reply.pcontent) + '</p>';
                                html += '<div class="review"><div class="likess"><i class="like" :class="likeClass" @click.stop="Like()"></i><span class="likes">{{ likes }}</span></div>';
                                html += '<div class="commentss"><i class="icon ice-message"></i><span class="comments">{{ commentscount }}</span></div></div>';
                                html += '</div>';
                            }
                        }

                        let container = $("#container");
                        $(container).append(html);
                        var selectPid = postidarray[0];
                        for (let i = 0; i < postidarray.length; i++) {
                            let vmp = new Vue({
                                el: '#post-' + postidarray[i],
                                data: {
                                    islike: false,
                                    likes: 0,
                                    commentscount: 0,
                                },
                                computed: {
                                    likeClass() {
                                        return this.islike ? 'icon ice-heart-on' : 'icon ice-heart-off';
                                    },
                                },
                                methods: {
                                    Like() {
                                        let icon = this.$el.querySelector('.icon');
                                        if (this.islike) {
                                            // 取消点赞
                                            this.likes--;
                                            icon.classList.remove('ice-heart-on');
                                            icon.classList.add('ice-heart-off');

                                            // 发送取消点赞请求
                                            $.ajax({
                                                url: "http://169.254.202.137:8080/unlike",
                                                type: "POST",
                                                data: { pid: pid, uid: user.uid },
                                                success: function (response) {

                                                },
                                                error: function (xhr, status, error) {
                                                    console.error(xhr.responseText);
                                                    // 在这里处理取消点赞错误响应
                                                }
                                            });
                                        } else {
                                            // 点赞
                                            this.likes++;
                                            icon.classList.remove('ice-heart-off');
                                            icon.classList.add('ice-heart-on', 'like-animation');

                                            // 发送点赞请求
                                            $.ajax({
                                                url: "http://169.254.202.137:8080/like",
                                                type: "POST",
                                                data: { pid: pid, uid: user.uid },
                                                success: function (response) {

                                                },
                                                error: function (xhr, status, error) {
                                                    console.error(xhr.responseText);
                                                    // 在这里处理点赞错误响应
                                                }
                                            });
                                        }
                                        this.islike = !this.islike;
                                    },
                                    PubComment() {
                                        let pcontent = $('.input').val()

                                        if (pcontent == "" || pcontent == undefined || pcontent == null) {
                                            layui.layer.msg('你还没有回复', { icon: 2, time: 1500 }, function () {

                                            });
                                            return;
                                        }

                                        let formdata = new FormData()
                                        formdata.append("pcontent", contentToUTF16(pcontent));
                                        formdata.append("publisheruid", user.uid);
                                        formdata.append("parentId", selectPid);

                                        $.ajax({
                                            url: 'http://169.254.202.137:8080/PubCommentOrReply?',
                                            data: formdata,
                                            processData: false,
                                            contentType: false,
                                            type: 'Post',
                                            dataType: 'json',
                                            success: function (res) {
                                                if (res.code == 200) {
                                                    layui.layer.msg('发布成功', { icon: 1, time: 1500 }, function () {
                                                        $('.input').val('');
                                                    });
                                                }
                                            }
                                        })
                                    },
                                    selectReplyPid() {
                                        selectPid = postidarray[i];

                                        $('.input').prop('placeholder', '发布你的回复')
                                    }
                                }
                            });
                            // 使用jquery的ajax方法，向后端发送第二次请求，获取帖子的点赞数和评论数
                            $.ajax({
                                type: "GET",
                                url: "http://169.254.202.137:8080/GetLikeAndComment?pid=" + postidarray[i] + "&uid=" + user.uid, // 后端的Servlet路径，加上帖子ID参数
                                dataType: "json", // 预期返回的数据类型是json
                                success: function (data) {
                                    // 如果请求成功，将返回的数据赋值给vue对象的data属性，实现数据的双向绑定
                                    vmp.likes = data.data.likes; // 将返回的点赞数赋值给likes
                                    vmp.commentscount = data.data.commentscount; // 将返回的评论数赋值给comments
                                    vmp.islike = data.data.islike
                                }
                            });
                        }
                        if (commentidarray.length >= 1) {
                            for (let c = 0; c < commentidarray.length; c++) {
                                let vmc = new Vue({
                                    el: '#comment-' + commentidarray[c],
                                    data: {
                                        islike: false,
                                        likes: 0,
                                        commentscount: 0,
                                    },
                                    computed: {
                                        likeClass() {
                                            return this.islike ? 'icon ice-heart-on' : 'icon ice-heart-off';
                                        },
                                    },
                                    methods: {
                                        Like() {
                                            let icon = this.$el.querySelector('.icon');
                                            if (this.islike) {
                                                // 取消点赞
                                                this.likes--;
                                                icon.classList.remove('ice-heart-on');
                                                icon.classList.add('ice-heart-off');

                                                // 发送取消点赞请求
                                                $.ajax({
                                                    url: "http://169.254.202.137:8080/unlike",
                                                    type: "POST",
                                                    data: { pid: commentidarray[c], uid: user.uid },
                                                    success: function (response) {

                                                    },
                                                    error: function (xhr, status, error) {
                                                        console.error(xhr.responseText);
                                                        // 在这里处理取消点赞错误响应
                                                    }
                                                });
                                            } else {
                                                // 点赞
                                                this.likes++;
                                                icon.classList.remove('ice-heart-off');
                                                icon.classList.add('ice-heart-on');

                                                // 发送点赞请求
                                                $.ajax({
                                                    url: "http://169.254.202.137:8080/like",
                                                    type: "POST",
                                                    data: { pid: commentidarray[c], uid: user.uid },
                                                    success: function (response) {

                                                    },
                                                    error: function (xhr, status, error) {
                                                        console.error(xhr.responseText);
                                                        // 在这里处理点赞错误响应
                                                    }
                                                });
                                            }
                                            this.islike = !this.islike;
                                        },
                                        selectReplyPid() {
                                            selectPid = commentidarray[c];

                                            let replyuser = $(this.$el).find("span.user").text()
                                            $('.input').prop('placeholder', '回复 @' + replyuser)
                                        }
                                    }

                                });
                                // 使用jquery的ajax方法，向后端发送第二次请求，获取帖子的点赞数和评论数
                                $.ajax({
                                    type: "GET",
                                    url: "http://169.254.202.137:8080/GetLikeAndComment?pid=" + commentidarray[c] + "&uid=" + user.uid, // 后端的Servlet路径，加上帖子ID参数
                                    dataType: "json", // 预期返回的数据类型是json
                                    success: function (data) {
                                        // 如果请求成功，将返回的数据赋值给vue对象的data属性，实现数据的双向绑定
                                        vmc.likes = data.data.likes; // 将返回的点赞数赋值给likes
                                        vmc.commentscount = data.data.commentscount; // 将返回的评论数赋值给comments
                                        vmc.islike = data.data.islike;
                                    }
                                });
                            }
                        }

                        if (replyidarray.length >= 1) {
                            for (let j = 0; j < replyidarray.length; j++) {
                                let vmr = new Vue({
                                    el: '#reply-' + replyidarray[j],
                                    data: {
                                        islike: false,
                                        likes: 0,
                                        commentscount: 0,
                                    },
                                    computed: {
                                        likeClass() {
                                            return this.islike ? 'icon ice-heart-on' : 'icon ice-heart-off';
                                        },
                                    },
                                    methods: {
                                        Like() {
                                            let icon = this.$el.querySelector('.icon');
                                            if (this.islike) {
                                                // 取消点赞
                                                this.likes--;
                                                icon.classList.remove('ice-heart-on');
                                                icon.classList.add('ice-heart-off');

                                                // 发送取消点赞请求
                                                $.ajax({
                                                    url: "http://169.254.202.137:8080/unlike",
                                                    type: "POST",
                                                    data: { pid: replyidarray[j], uid: user.uid },
                                                    success: function (response) {

                                                    },
                                                    error: function (xhr, status, error) {
                                                        console.error(xhr.responseText);
                                                        // 在这里处理取消点赞错误响应
                                                    }
                                                });
                                            } else {
                                                // 点赞
                                                this.likes++;
                                                icon.classList.remove('ice-heart-off');
                                                icon.classList.add('ice-heart-on');

                                                // 发送点赞请求
                                                $.ajax({
                                                    url: "http://169.254.202.137:8080/like",
                                                    type: "POST",
                                                    data: { pid: replyidarray[j], uid: user.uid },
                                                    success: function (response) {

                                                    },
                                                    error: function (xhr, status, error) {
                                                        console.error(xhr.responseText);
                                                        // 在这里处理点赞错误响应
                                                    }
                                                });
                                            }
                                            this.islike = !this.islike;
                                        },
                                    }
                                });
                                // 使用jquery的ajax方法，向后端发送第二次请求，获取帖子的点赞数和评论数
                                $.ajax({
                                    type: "GET",
                                    url: "http://169.254.202.137:8080/GetLikeAndComment?pid=" + replyidarray[j] + "&uid=" + user.uid, // 后端的Servlet路径，加上帖子ID参数
                                    dataType: "json", // 预期返回的数据类型是json
                                    success: function (data) {
                                        // 如果请求成功，将返回的数据赋值给vue对象的data属性，实现数据的双向绑定
                                        vmr.likes = data.data.likes; // 将返回的点赞数赋值给likes
                                        vmr.commentscount = data.data.commentscount; // 将返回的评论数赋值给comments
                                        vmr.islike = data.data.islike
                                    }
                                });
                            }
                        }
                    },
                    error: function (error) {
                        // 如果请求失败，显示错误信息
                        alert("请求失败：" + error);
                    }

                });
                // 获取容器元素对象
                let element = $("#container");


                // 定义一个变量，用于存储弹出层的索引
                let index;

                // 监听容器元素的 mouseover 事件
                element.on("mouseover", "time", function (e) {
                    // 获取触发事件的目标元素
                    let target = e.target;

                    // 判断目标元素是否是 time 标签
                    if (target.tagName === "TIME") {
                        // 获取 time 标签的 lay-src 属性的值
                        let datetime = target.getAttribute("lay-src");

                        let date = new Date(datetime);

                        let hour = date.getHours();
                        let minute = date.getMinutes();
                        let month = (date.getMonth() + 1);
                        let day = date.getDate();
                        let year = date.getFullYear();

                        let timestr = "";
                        if (hour <= 12)
                            timestr += "上午"
                        else
                            timestr += "下午"

                        timestr += hour + ": " + minute + " ·" + month + "月" + day + "，" + year;

                        // 使用 layer 的 tips 方法，显示 time 标签的值
                        index = layer.tips(timestr, target, {
                            tips: [3, '#3595CC'], // 设置提示框的方向和颜色
                            time: 0 // 设置提示框不自动关闭
                        });
                    }
                });

                // 监听容器元素的 mouseout 事件
                element.on("mouseout", "time", function (e) {
                    // 获取触发事件的目标元素
                    let target = e.target;

                    // 判断目标元素是否是 time 标签
                    if (target.tagName === "TIME") {
                        // 使用 layer 的 close 方法，隐藏 time 标签的值
                        layer.close(index);
                    }
                });
            });
            // 展开回复
            $("#container").on('click', '.comment .commentss', function () {
                let replyCount = $(this).find('.comments').text()

                let review = $(this).parent(".review").parent('.comment').nextAll('.reply:lt(' + replyCount + ')')


                if ($(review).hasClass('hiddenReply')) {
                    $(review).removeClass('hiddenReply')
                } else {
                    $(review).addClass('hiddenReply')
                }

            })
        </script>
        <div class="layui-col-md4">
            <div class="grid-demo grid-demo-bg1"></div>
        </div>
    </div>
</body>

</html>